import React from "react";
import style_x from '../assets/css/scroll_figure_x.scss'
import style_y from '../assets/css/scroll_figure_y.scss'

export default class ScrollFigure extends React.Component {
    constructor(props) {
        super(props);
        // console.log(this.props)
        let isX = this.props.direction === 'x'
        this.state = {
            isX,
            style: isX ? style_x : style_y,
            animate: null
        }
    }

    render() {
        const {style} = this.state
        return (
            <div className={style.wrapper}
                 onMouseOver={() => this.stopMove()}
                 onMouseOut={() => this.startMove()}
            >
                <div className={style.boxes}>
                    {this.props.children(style)}
                </div>
            </div>
        )
    }

    stopMove() {
        this.state.animate.pause()
    }

    startMove() {
        this.state.animate.play()
    }

    componentDidMount() {
        const optionX = {
            name: `.${this.state.style.box}`,
            direction: 'X',
            chose: 'x',
            distance: 1520,
            boxwidth: 190,
            speed: 19000
        }
        const optionY = {
            name: `.${this.state.style.box}`,
            direction: 'Y',
            chose: 'y',
            distance: 2000,
            boxwidth: 250,
            speed: 21000
        }
        this.animeStart(this.state.isX ? optionX : optionY)
    }

    animeStart({name, direction, chose, distance, boxwidth, speed} = {}) {
        const anime = require('animejs').default

        let xTrans = [];
        anime.set(name, {
            ['translate' + direction]: function (el, i, l) {
                xTrans[i] = {[chose]: i * boxwidth};
                return i * boxwidth;
            },
        });
        const animate = anime({
            targets: xTrans,
            duration: speed, //走一周持续时间
            easing: 'linear',
            [chose]: `+=${distance}`,
            loop: true,
            update: (anime) => {
                anime.set(name, {
                    ['translate' + direction]: function (el, i, l) {
                        return xTrans[i][chose] % distance
                    }
                });
            }
        })
        this.setState({
            animate
        })
    }
}
